﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace UpdaterForm
{
    public class Settings
    {
        private const string ConfFile = @".\Conf.xml";
        private static Configuration _instance;

        private Settings()
        {
        }

        public static Configuration Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = LoadConf();
                }
                return _instance;
            }
        }

        private static Configuration LoadConf()
        {
            try
            {
                var serializer = new XmlSerializer(typeof(Configuration));
                using (var reader = new StreamReader(ConfFile))
                {
                    return (Configuration)serializer.Deserialize(reader);
                }
            }
            catch (Exception)
            {
                return new Configuration
                
                {   Data = new Data{AppData = new List<AppData>()},
                    DateFormat = "yyyyMMdd",
                    MessageFileName = "readme.txt"
                };
            }

        }

        public static void SaveConf()
        {
            //TODO: add exception handling for file not found ir invalid directory
            if (_instance != null)
            {
                var serializer = new XmlSerializer(typeof(Configuration));
                using (var writer = new StreamWriter(ConfFile))
                {
                    serializer.Serialize(writer, _instance);
                }
            }
        }
    }
}